from pymongo import MongoClient

conn = MongoClient('192.168.2.212', 27017)
db = conn.babogd  #连接mydb数据库，没有则自动创建
my_set=db.demo_db  #使用test_set集合，没有则自动创建

#my_set.insert_one({"name":"zhangsan","age":18})
#或
#my_set.insert_many({"name":"zhangsan","age":18})

def add_many():
    users=[{"name":"charlie","age":18},{"name":"qq","age":15}]
    my_set.insert_many(users)

def findDemo():
    # 查询全部
    for i in my_set.find():
        print(i)
    # 查询name=zhangsan的

    print("---------------------------")
    for i in my_set.find({"name": "zhangsan"}):
        print(i)

    print("---------------------------")
    print(my_set.find_one({"name": "zhangsan"}))
    pass
def multiPath():
    dic = {"name": "zhangsan",
           "age": 18,
           "contact": {
               "email": "1234567@qq.com",
               "iphone": "11223344"}
           }
    my_set.insert_one(dic)
def findMulitPath():
    # 多级目录用. 连接
    for i in my_set.find({"contact.iphone": "11223344"}):
        print(i)
    # 输出：{'name': 'zhangsan', '_id': ObjectId('58c4f99c4fc9d42e0022c3b6'), 'age': 18, 'contact': {'email': '1234567@qq.com', 'iphone': '11223344'}}

    result = my_set.find_one({"contact.iphone": "11223344"})
    print("-------------------------------------")
    print("contact:email = " + result["contact"]["email"])
    pass


def multiPathArr():
    dic = {"name": "lisi",
           "age": 18,
           "contact": [
               {
                   "email": "111111@qq.com",
                   "iphone": "111"},
               {
                   "email": "222222@qq.com",
                   "iphone": "222"}
           ]}
    my_set.insert_one(dic)
def multiPathArrFind():
    result1 = my_set.find_one({"contact.1.iphone": "222"})
    print(result1)
    # 输出：{'age': 18, '_id': ObjectId('58c4ff574fc9d43844423db2'), 'name': 'lisi', 'contact': [{'iphone': '111', 'email': '111111@qq.com'}, {'iphone': '222', 'email': '222222@qq.com'}]}

    # 修改
    result = my_set.update({"contact.1.iphone": "222"}, {"$set": {"contact.1.email": "222222@qq.com"}})
    print(result1["contact"][1]["email"])
    pass

multiPathArrFind()